package com.ruoyi.web.controller.consumerAdmin;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.consumer.constance.AgentPoxyLevelEnum;
import com.ruoyi.consumer.domain.*;
import com.ruoyi.consumer.domain.bind.BindDTO;
import com.ruoyi.consumer.domain.param.UserQueryParam;
import com.ruoyi.consumer.service.impl.*;
import com.ruoyi.consumer.utils.TableDataUtil;
import com.ruoyi.consumer.utils.redis.CompanyCache;
import com.ruoyi.system.service.impl.SysDeptServiceImpl;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;



/**
 * @author: lizhouwei
 * @ date : 2023/10/10
 * @description:
 */
@Api(tags = "公司后台相关接口")
@RestController
@RequestMapping("/api/company")
public class CompanyAdminController {

    @Autowired
    private CUserServiceImpl userService;

    @Autowired
    private CCompanyServiceImpl companyService;

    @Autowired
    private CLytxUserServiceImpl lytxUserService;

    @Autowired
    private SysUserServiceImpl sysUserService;

    @Autowired
    private CompanyBindServiceImpl bindService;

    @Autowired
    private SysDeptServiceImpl deptService;

    @Autowired
    private CompanyCache companyCache;

    @Autowired
    private CAgentRelationsServiceImpl agentService;


    /**
     * 绑定员工给车队长
     *
     * @param data
     * @return
     */
    @ApiOperation("绑定员工")
    @PostMapping("/bindStaff")
    public AjaxResult bindStaff(@RequestBody BindDTO data) {
        Assert.notNull(data, "用户信息不能为空");
        String userName = data.getUserName();
        String userPhone = data.getUserPhone();
        Long sysUserId = data.getSysUserId();

        Assert.notNull(userName, "用户姓名不能为空");
        Assert.notNull(userPhone, "用户手机号不能为空");

        //查询用户信息
        CUser cUser = new CUser();
        cUser.setUserName(userName);
        cUser.setUserPhone(userPhone);
        List<CUser> cUsers = userService.selectCUserList(cUser);
        if (cUsers.size() == 0) {
            return AjaxResult.error("用户不存在");
        }
        if (companyCache.getCompanyInfo(cUsers.get(0).getUserId()) != null) {
            return AjaxResult.error("用户已绑定公司");
        }
        Long userAdminId = SecurityUtils.getUserId();
        SysUser sysUser = sysUserService.selectUserById(userAdminId);
        if (sysUser == null) {
            return AjaxResult.error("管理员不存在");
        }
        //查询当前管理员所处公司
        CCompany company = new CCompany();
        company.setCompanDept(Math.toIntExact(sysUser.getDeptId()));
        List<CCompany> cCompanies = companyService.selectCCompanyList(company);
        if (cCompanies.size() == 0) {
            return AjaxResult.error("管理员所处公司不存在");
        }
        //绑定员工
        CompanyBind companyBind = new CompanyBind();
        companyBind.setConsumerId(cUsers.get(0).getUserId());
        if (bindService.selectCompanyBindList(companyBind).size() > 0) {
            return AjaxResult.error("用户已绑定公司");
        }
        companyBind.setDeptId(sysUser.getDeptId());
        companyBind.setSysUserId(sysUserId);
        companyBind.setCompanyId(cCompanies.get(0).getCompanyId());
        bindService.insertCompanyBind(companyBind);

        //更新用户companyId
        CUser user = new CUser();
        user.setUserId(cUsers.get(0).getUserId());
        user.setCompanyId(cCompanies.get(0).getCompanyId());
        int i = userService.updateCUser(user);

        if (i > 0) {
            //缓存公司信息
            companyCache.cacheCompanyInfo(cUsers.get(0).getUserId(), cCompanies.get(0).getCompanyName());
            return AjaxResult.success("绑定成功");
        } else {
            return AjaxResult.error("绑定失败");
        }
    }

    /**
     * 直接绑定员工到公司
     *
     * @param data
     * @return
     */
    @ApiOperation("直接绑定员工到公司")
    @PostMapping("/bind-staff-to-company")
    public AjaxResult bindStaffToCompany(@RequestBody BindDTO data) {
        Assert.notNull(data, "用户信息不能为空");
        String userName = data.getUserName();
        String userPhone = data.getUserPhone();
        System.out.println(data);
        Assert.notNull(userName, "用户姓名不能为空");
        Assert.notNull(userPhone, "用户手机号不能为空");

        //查询用户信息
        CUser cUser = new CUser();
        cUser.setUserName(userName);
        cUser.setUserPhone(userPhone);
        List<CUser> cUsers = userService.selectCUserList(cUser);
        if (cUsers.size() == 0) {
            return AjaxResult.error("用户不存在");
        }
        if (companyCache.getCompanyInfo(cUsers.get(0).getUserId()) != null) {
            return AjaxResult.error("用户已绑定公司");
        }
        Long userAdminId = SecurityUtils.getUserId();
        SysUser sysUser = sysUserService.selectUserById(userAdminId);
        if (sysUser == null) {
            return AjaxResult.error("管理员不存在");
        }
        //查询当前管理员所处公司
        CCompany company = new CCompany();
        company.setCompanDept(Math.toIntExact(sysUser.getDeptId()));
        List<CCompany> cCompanies = companyService.selectCCompanyList(company);
        if (cCompanies.size() == 0) {
            return AjaxResult.error("管理员所处公司不存在");
        }
        //绑定员工
        CompanyBind companyBind = new CompanyBind();
        companyBind.setConsumerId(cUsers.get(0).getUserId());
        if (bindService.selectCompanyBindList(companyBind).size() > 0) {
            return AjaxResult.error("用户已绑定公司");
        }
        companyBind.setDeptId(sysUser.getDeptId());
        companyBind.setCompanyId(cCompanies.get(0).getCompanyId());
        bindService.insertCompanyBind(companyBind);
        //更新用户companyId
        CUser user = new CUser();
        user.setUserId(cUsers.get(0).getUserId());
        user.setCompanyId(cCompanies.get(0).getCompanyId());
        int i = userService.updateCUser(user);
        if (i > 0) {
            //缓存公司信息
            companyCache.cacheCompanyInfo(cUsers.get(0).getUserId(), cCompanies.get(0).getCompanyName());
            return AjaxResult.success("绑定成功");
        } else {
            return AjaxResult.error("绑定失败");
        }
    }


    /**
     * 解绑员工
     *
     * @param data
     * @return
     */
    @Transactional
    @ApiOperation("解绑员工")
    @PostMapping("/unbindStaff")
    public AjaxResult unbindStaff(@RequestBody CUser data) {
        Integer userId = data.getUserId();
        Assert.notNull(userId, "用户id不能为空");
        //查询用户信息
        CUser cUser = userService.selectCUserByUserId(userId);
        if (cUser == null) {
            return AjaxResult.error("用户不存在");
        }
        if (cUser.getCompanyId() == 0) {
            return AjaxResult.error("用户未绑定公司");
        }
        if (cUser.getUserRole() == 1) {
            CompanyBind companyBind = new CompanyBind();
            companyBind.setSysUserId(Long.valueOf(userId));
            List<CompanyBind> companyBinds = bindService.selectCompanyBindList(companyBind);
            if (companyBinds.size() > 0) {
                return AjaxResult.error("该车队长下还有员工,请先解绑员工");
            }
        }
        Long userAdminId = SecurityUtils.getUserId();
        SysUser sysUser = sysUserService.selectUserById(userAdminId);
        if (sysUser == null) {
            return AjaxResult.error("管理员不存在");
        }
        //查询当前管理员所处公司
        CCompany company = new CCompany();
        company.setCompanDept(Math.toIntExact(sysUser.getDeptId()));
        List<CCompany> cCompanies = companyService.selectCCompanyList(company);
        if (cCompanies.isEmpty()) {
            return AjaxResult.error("管理员所处公司不存在");
        }
        //解绑员工
        CompanyBind companyBind = new CompanyBind();
        companyBind.setDeptId(Long.valueOf(cCompanies.get(0).getCompanDept()));
        companyBind.setConsumerId(userId);
        List<CompanyBind> companyBinds = bindService.selectCompanyBindList(companyBind);
        if (companyBinds.size() == 0) {
            return AjaxResult.error("用户未绑定公司");
        }
        bindService.deleteCompanyBindByBindId(companyBinds.get(0).getBindId());
        //更新员工表
        CUser user = new CUser();
        user.setUserId(userId);
        user.setCompanyId(0);
        user.setUserRole(0);
        int i = userService.updateCUser(user);
        //将代理表中的数据删除
        CAgentRelations agent = new CAgentRelations();
        agent.setSuperUserId(userId);
        agent.setAgentLevel(AgentPoxyLevelEnum.LEVEL_ONE.getDescription());
        List<CAgentRelations> cAgentRelations = agentService.selectCAgentRelationsList(agent);
        if (!cAgentRelations.isEmpty()) {
            for (CAgentRelations cAgentRelation : cAgentRelations) {
                cAgentRelation.setIsDelete(1);
                agentService.updateCAgentRelations(cAgentRelation);
            }
            //将业务员表中的数据删除
            CLytxUser lytxUser = new CLytxUser();
            lytxUser.setUserId(userId);
            List<CLytxUser> cLytxUsers = lytxUserService.selectCLytxUserList(lytxUser);
            if (!cLytxUsers.isEmpty())
                lytxUserService.deleteCLytxUserByLytxId(cLytxUsers.get(0).getLytxId());
        }


        //缓存中移除公司信息
        companyCache.removeCompanyInfo(cUser.getUserId());
        return AjaxResult.success("解绑成功");
    }


    /**
     * 根据手机号查找用户
     */
    @ApiOperation("根据手机号查找用户")
    @PostMapping("/searchUserByPhone")
    public AjaxResult searchUserByPhone(@RequestBody CUser data) {
        PageHelper.startPage(1, 20);
        PageHelper.orderBy("create_time desc");
        Assert.notNull(data, "用户信息不能为空");
        CUser cUser = new CUser();
        cUser.setUserPhone(data.getUserPhone());
        cUser.setUserName(data.getUserName());
        List<CUser> Users = userService.selectCUserList(cUser);
        List<CUser> cUsers = new ArrayList<>();
        for (CUser user : Users) {
            if (user.getCompanyId() == 0 || user.getCompanyId() == data.getCompanyId())
                cUsers.add(user);
        }
        return AjaxResult.success(cUsers);
    }

    /**
     * 查找用户
     */
    @ApiOperation("查找用户")
    @PostMapping("/searchUser")
    public AjaxResult searchUser(@RequestBody CUser data) {
        Assert.notNull(data, "用户信息不能为空");

        String userName = data.getUserName();
        String userPhone = data.getUserPhone();

        Assert.notNull(userName, "用户姓名不能为空");
        Assert.notNull(userPhone, "用户手机号不能为空");
        //正则校验手机号
        String regex = "^1[3456789]\\d{9}$";
        if (!userPhone.matches(regex)) {
            return AjaxResult.error("手机号格式不正确");
        }
        //查询用户信息
        CUser cUser = new CUser();
        cUser.setUserName(userName);
        cUser.setUserPhone(userPhone);
        List<CUser> cUsers = userService.selectCUserList(cUser);
        if (cUsers.size() == 0) {
            return AjaxResult.error("用户不存在");
        }
        UserQueryParam userQueryParam = new UserQueryParam();
        userQueryParam.setUserId(cUsers.get(0).getUserId());
        userQueryParam.setUserPhone(cUsers.get(0).getUserPhone());
        userQueryParam.setUserNick(cUsers.get(0).getUserNick());
        userQueryParam.setUserHeader(cUsers.get(0).getUserHeader());
        userQueryParam.setUserName(cUsers.get(0).getUserName());
        userQueryParam.setUserRole(cUsers.get(0).getUserRole());
        String companyName = companyCache.getCompanyInfo(cUsers.get(0).getUserId());
        if (companyName != null)
            userQueryParam.setCompanyName(companyName);
        else
            userQueryParam.setCompanyName("暂未绑定公司");

        return AjaxResult.success(userQueryParam);
    }

    //查询公司中的小队长
    @PreAuthorize("@ss.hasRole('common')")
    @ApiOperation("查询公司中的小队长")
    @GetMapping("/search-driver-leader")
    public AjaxResult searchDriverLeader() {
        List<AjaxResult> driver_leader = new ArrayList<>();
        Long userAdminId = SecurityUtils.getUserId();
        System.out.println("当前用户id:" + userAdminId);
        SysUser sysUser = sysUserService.selectUserById(userAdminId);
        if (sysUser == null) {
            return AjaxResult.error("管理员不存在");
        }
        //查询当前管理员所处公司
        SysDept sysDept = deptService.selectDeptById(sysUser.getDeptId());
        if (sysDept == null) {
            return AjaxResult.error("管理员所处公司不存在");
        }

        CCompany company = new CCompany();
        company.setCompanDept(Math.toIntExact(sysUser.getDeptId()));
        List<CCompany> cCompanies = companyService.selectCCompanyList(company);
        if (cCompanies.size() == 0) {
            return AjaxResult.error("管理员所处公司不存在");
        }


        String ancestors = sysDept.getAncestors();
        String[] split = ancestors.split(",");
        if (split.length == 2) {
            //他是消费者公司,查询对应的子车队长岗位

            //查询对应的小队长
            CUser user = new CUser();
            user.setUserRole(1);
            user.setCompanyId(cCompanies.get(0).getCompanyId());
            List<CUser> sysUsers = userService.selectCUserList(user);
            System.out.println("对应小队长:" + sysUsers);

            if (sysUsers.size() == 0) {
                return AjaxResult.success("公司中暂无小队长");
            } else {
                for (CUser sysUser1 : sysUsers) {
                    AjaxResult ajaxResult = new AjaxResult();
                    ajaxResult.put("sysUserId", sysUser1.getUserId());
                    ajaxResult.put("userName", sysUser1.getUserName());
                    ajaxResult.put("userPhone", sysUser1.getUserPhone());
                    driver_leader.add(ajaxResult);
                }

            }
        }
        return AjaxResult.success(driver_leader);
    }

    //按管理员相应角色获取子用户
    @ApiOperation("按管理员相应角色获取子用户")
    @GetMapping("get-user-list")
    public TableDataInfo getUserList() {
        Long userAdminId = SecurityUtils.getUserId();
        SysUser sysUser = sysUserService.selectUserById(userAdminId);
        Assert.notNull(sysUser, "管理员不存在");
        //查询当前管理员所处公司
        SysDept sysDept = deptService.selectDeptById(sysUser.getDeptId());
        System.out.println("当前管理员所处公司id:" + sysDept.getDeptId());
        Assert.notNull(sysDept, "管理员所处公司不存在");
        String ancestors = sysDept.getAncestors();
        String[] split = ancestors.split(",");
        List<UserQueryParam> userQueryParams = new ArrayList<>();
        if (split.length == 2) {
            //一级管理员查询所有公司用户
            CompanyBind companyBind = new CompanyBind();
            companyBind.setDeptId(sysUser.getDeptId());
            List<CompanyBind> companyBinds = bindService.selectCompanyBindList(companyBind);
            //取出用户
            List<CUser> users = new ArrayList<>();
            for (CompanyBind bind : companyBinds) {
                CUser user = userService.selectCUserByUserId(bind.getConsumerId());
                users.add(user);
            }

            for (CUser user : users) {
                if (user == null) {
                    continue;
                }
                UserQueryParam userQueryParam = new UserQueryParam();
                userQueryParam.setUserId(user.getUserId());
                userQueryParam.setUserPhone(user.getUserPhone());
                userQueryParam.setUserNick(user.getUserNick());
                userQueryParam.setUserHeader(user.getUserHeader());
                userQueryParam.setUserName(user.getUserName());
                userQueryParam.setUserRole(user.getUserRole());
                String companyName = companyCache.getCompanyInfo(user.getUserId());
                if (companyName != null)
                    userQueryParam.setCompanyName(companyName);
                else
                    userQueryParam.setCompanyName("暂未绑定公司");
                userQueryParams.add(userQueryParam);
            }
        }
        if (split.length == 3) {
            //车队长查询对应手下用户
            CompanyBind companyBind = new CompanyBind();
            companyBind.setDeptId(sysDept.getParentId());
            companyBind.setSysUserId(sysUser.getUserId());
            List<CompanyBind> companyBinds = bindService.selectCompanyBindList(companyBind);
            //取出用户
            List<CUser> users = new ArrayList<>();
            for (CompanyBind bind : companyBinds) {
                CUser user = userService.selectCUserByUserId(bind.getConsumerId());
                users.add(user);
            }
            for (CUser user : users) {
                UserQueryParam userQueryParam = new UserQueryParam();
                userQueryParam.setUserId(user.getUserId());
                userQueryParam.setUserPhone(user.getUserPhone());
                userQueryParam.setUserNick(user.getUserNick());
                userQueryParam.setUserHeader(user.getUserHeader());
                userQueryParam.setUserName(user.getUserName());
                userQueryParam.setUserRole(user.getUserRole());
                String companyName = companyCache.getCompanyInfo(user.getUserId());
                if (companyName != null)
                    userQueryParam.setCompanyName(companyName);
                else
                    userQueryParam.setCompanyName("暂未绑定公司");
                userQueryParams.add(userQueryParam);
            }

        }
        return TableDataUtil.getDataTable(userQueryParams);
    }

    //获取当前公司id
    @ApiOperation("获取当前公司id")
    @GetMapping("/get-company-id")
    public Integer getCompanyId() {
        Long userAdminId = SecurityUtils.getUserId();
        SysUser sysUser = sysUserService.selectUserById(userAdminId);
        Assert.notNull(sysUser, "管理员不存在");
        //查询当前管理员所处公司
        SysDept sysDept = deptService.selectDeptById(sysUser.getDeptId());
        CCompany company = new CCompany();
        company.setCompanDept(Math.toIntExact(sysUser.getDeptId()));
        List<CCompany> cCompanies = companyService.selectCCompanyList(company);
        if (cCompanies.size() == 0) {
            return null;
        }
        return cCompanies.get(0).getCompanyId();
    }

}
